﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace WPFDemoMVVM.Behaviors
{
    public class SelectedItemsBehavior: Behavior<MultiSelector>
    {

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SelectionChanged += OnSelectionChanged;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.SelectionChanged -= OnSelectionChanged;
        }

        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selector = (MultiSelector)sender;
            //SetBindableSelectedItems(selector, selector.SelectedItems);
            BindableSelectedItems =selector.SelectedItems;
            selector.GetBindingExpression(BindableSelectedItemsProperty)?.UpdateSource();
        }

        #region Bindable SelectedItems

        //public static IList GetBindableSelectedItems(DependencyObject obj)
        //{
        //    return (IList)obj.GetValue(BindableSelectedItemsProperty);
        //}

        //public static void SetBindableSelectedItems(DependencyObject obj, IList value)
        //{
        //    obj.SetValue(BindableSelectedItemsProperty, value);
        //}


        //public static readonly DependencyProperty BindableSelectedItemsProperty =
        //    DependencyProperty.RegisterAttached("BindableSelectedItems", typeof(IList)
        //        , typeof(SelectedItemsBehavior), 
        //        new PropertyMetadata(null));



        public IList BindableSelectedItems
        {
            get { return (IList)GetValue(BindableSelectedItemsProperty); }
            set { SetValue(BindableSelectedItemsProperty, value); }
        }

        public static readonly DependencyProperty BindableSelectedItemsProperty =
            DependencyProperty.Register("BindableSelectedItems", typeof(IList), typeof(SelectedItemsBehavior), new PropertyMetadata(null));



        #endregion

    }
}
